﻿using System;
using System.Diagnostics;
using System.Linq;
using NotifyPilot.Models;
using NotifyPilot.WCF.Helpers;
using NotifyPilot.WCF.NotifyClients;

namespace NotifyPilot.WCF
{
    public class CoreEventConnectors
    {
        private static readonly Type[] NotifyTypes = Helpers.Helpers.GetNotifyClientClasses(typeof(INotifyClient)).ToArray();
        private static readonly string TFSRootUrl = ConfigurationHelpers.GetValue("TFSRootUrl");

        private static readonly ServicesConfiguration[] ServicesConfigurations =
            Helpers.Helpers.DeserialiseXmlFromFile<ServicesConfiguration[]>(ConfigPath.PathServices);

        public void Notify(string eventXml)
        {
            // eventXml = this.getExample(); // Use it for rapid debug/check
            foreach (var notifyType in NotifyTypes)
            {
                Type type = notifyType;
                var serviceConfig = ServicesConfigurations.FirstOrDefault(p => p.ServiceName == type.Name &&
                    p.EventsClasses.Count(c => c.Use) > 0);
                var eventType = TFSContentObjectFactory.GetEventClass(eventXml);
                if (serviceConfig != null &&
                    serviceConfig.EventsClasses.Any(c => c.EventType == eventType && c.Use))
                {
                    var parameters = new object[] { eventXml, TFSRootUrl };
                    //  ThreadPool.QueueUserWorkItem(delegate
                    // {
                    try
                    {
                        var notifyObject = (INotifyClient)Activator.CreateInstance(type, parameters);
                        notifyObject.Post();
                    }
                    catch (Exception ex)
                    {
                        EventLog.WriteEntry(Helpers.Helpers.NotifyLogSource,
                            String.Format("Notify Client Error [{0}]",
                                type.FullName) + ex.StackTrace,
                            EventLogEntryType.Error);
                    }
                    // });
                }
            }
        }
    }
}